package com.lzx.adx.report.support.strategy.v2.media;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@MediaType(MediaChannelConstant.XA_FISH)
public class XaFishCallBackStrategy extends AbstractCallback{

    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);

        String callback = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        log.info("dspId{},请求流水号{}回传给西安小鱼的地址为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), callback);
        if (!callback.contains("__EVENT__")) {
            log.info("dspId{},请求流水号{}回传给西安小鱼的地址不包含转化回传信息__EVENT__ 不做回传", reportDTO.getDspId(), reportDTO.getBizRequestId());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String replaceCallback = callback.replace("__EVENT__", eventType);
        //拼接完整的请求参数
        log.info("账号id{},请求id{} 给西安小鱼上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), replaceCallback);
        String result = HttpUtil.get(replaceCallback);
        log.info("账号id{},请求id{} 给西安小鱼上报回传结果为 {}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);
        return ResponseEntity.ok(new Result<>());
    }
}
